import iButton from '@/components/carGoods/i-button.vue'
import carInfoHeader from '@/components/afterSales/carInfoHeader.vue'
import addGoodsPopup from './components/addGoods-popup.vue'
import editServePopup from './components/edit-serve-popup.vue'
import installModePopup from './components/install-mode-popup.vue'

// 左滑操作组件
import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'

export default {
  components: {
    iButton,
    carInfoHeader,
    addGoodsPopup,
    editServePopup,
    installModePopup,
    uniSwipeAction,
    uniSwipeActionItem,
  },

  data() {
    return {
      // 实物产品列表
      productList: [],
      // 施工服务列表
      serveList: [],
      // 检测异常列表
      errList111: [
        {
          id: 1,
          label: '后保险杠状况',
          errName: '划痕一处',
          errDetail: '后保险杠外观',
          errImg:
            'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1212122793,4077899625&fm=11&gp=0.jpg',
        },
        {
          id: 2,
          label: '后保险杠状况',
          errName: '划痕一处',
          errDetail: '后保险杠外观',
          errImg:
            'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1212122793,4077899625&fm=11&gp=0.jpg',
        },
        {
          id: 3,
          label: '后保险杠状况',
          errName: '划痕一处',
          errDetail: '后保险杠外观',
          errImg:
            'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1212122793,4077899625&fm=11&gp=0.jpg',
        },
      ],
      // 安装方式的值
      installMode: {
        id: 0,
      },

      goodsShow: false, // 显示添加商品弹框
      serveShow: false, // 显示编辑服务弹框
      installModeShow: false, // 显示安装方式弹框
      freightVal: '', // 运费
      remark: '', // 备注
      rightOptions: [
        {
          text: '删除',
          style: {
            backgroundColor: '#EB5C02',
          },
        },
      ],
      pageLoading: false, //初始化加载效果
    }
  },

  computed: {
    // 金额价格部分
    priceData() {
      let obj = {
        goodsPrice: this.sumFn(this.productList, 'sale_Price', 'amount'),
        servePrice: this.sumFn(this.serveList, 'service_Price', 'serviceNum'),
      }
      obj.totalPrice =
        obj.goodsPrice + obj.servePrice + parseFloat(this.freightVal | 0)
      return obj
    },

    // 关联的 检测异常列表
    errList() {
      let list = this.$store.state.afterSales.selectedErrList
      return list
    },
  },

  filters: {
    // 过滤订单状态显示文字
    handleStatus(val) {
      let status = {
        0: '待提交',
        1: '待付款',
        2: '待施工',
      }
      return status[val]
    },

    // 处理金额数字小数点精度
    handleNumFloat(val) {
      return parseFloat(val).toFixed(2)
    },
  },

  onLoad() {
    this.$nextTick(() => {
      this.pageLoading = true
    })
  },

  onBackPress(e) {
    // 清空已选异常列表
    this.$store.commit('afterSales/setOrderErrList', [])
    return false
  },

  methods: {
    // 确定添加商品
    addGoodsChange({ type, data }) {
      console.log(data)
      // type为true则是点击确定按钮，false为继续添加商品
      if (type) {
        // 确定，商品信息
        this.goodsShow = false
        // if (this.productList.length > 0) {
        //   // 因可能会选择同一个商品,如果列表有重复，只需将数量叠加，不重复的新增进来
        //   data.map((item) => {
        //     let fIndex = -1
        //     if (item.id) {
        //       fIndex = this.productList.findIndex((li) => li.id === item.id)
        //     } else {
        //       fIndex = this.productList.findIndex(
        //         (li) => li.goods_Name === item.goods_Name
        //       )
        //     }
        //     if (fIndex !== -1) {
        //       // 找到重复的项，只需把数量叠加
        //       this.productList[fIndex].amount += item.amount
        //     } else {
        //       this.productList.push(item)
        //     }
        //   })

        // } else {
        //   this.productList = this.productList.concat(data)
        // }
        this.productList = this.productList.concat(data)
        this.GetServiceFeeByGoods(data)
      } else {
        // 继续添加，商品信息
        uni.navigateTo({
          url: '/pages_afterSales/selectOrderType/selectOrderType',
        })
      }
    },

    // 根据商品匹配相关服务
    async GetServiceFeeByGoods(list) {
      let data = {
        configuration_Id: this.$store.state.afterSales.carInfo.carId,
        getServiceFeeGoodsList: list
          .filter((item) => !!item.maintenance_Type_Id)
          .map((item) => ({
            maintenance_Type_Id: item.maintenance_Type_Id,
            maintenance_Goods_Id: item.id,
            count: item.amount,
          })),
      }
      try {
        const res = await this.$api.afterSales.GetServiceFeeByGoods(data)
        // this.serveList = res.data
        this.serveList = [...this.serveList, ...res.data]
        console.log(res.data)
      } catch (err) {
        console.log(err)
      }
    },

    // 减
    less(item) {
      if (item.amount <= 1) return
      item.amount -= 1
    },

    // 加
    add(item) {
      item.amount += 1
    },

    // 左滑删除商品项
    delChange(e) {
      // 需延迟移除数组项
      setTimeout(() => {
        this.productList.splice(e, 1)
      }, 100)
    },

    // 打开服务弹框
    servePopupOpen(item) {
      this.serveShow = true
      this.$nextTick(() => {
        this.$refs.serve.loadData(item)
      })
    },

    // 编辑服务确定/取消
    editServeChange({ type, data }) {
      // type为true则是点击确定按钮，false为继续添加商品
      this.serveShow = false
      if (type) {
        console.log('确定，商品信息', data)
      }
    },

    // 弹出安装方式
    installModeOpen() {
      this.installModeShow = true
      if (!this.installMode.id) return
      this.$nextTick(() => {
        this.$refs.installMode.selected(this.installMode)
      })
    },

    // 安装方式弹框确定
    installModeChange(data) {
      this.installMode = data
      console.log(data)
      this.installModeShow = false
    },

    // 计算商品金额、服务金额的各的总价
    sumFn(list, priceKey, count) {
      let sum = 0
      list.map((item) => {
        if (priceKey !== 'sale_Price') {
          sum += parseFloat(item[priceKey]) * item[count]
        } else if (!item.isVisualGoods) {
          sum += parseFloat(item[priceKey]) * item[count]
        }
        // sum += parseFloat(item[priceKey]) * item[count]
      })
      return sum
    },

    // 取消 返回上一页
    cancel() {
      uni.showModal({
        title: '提示',
        content: '确认取消新建该订单吗？',
        confirmColor: '#FBB000',
        success: function (res) {
          if (res.confirm) {
            uni.navigateBack({
              delta: 1,
            })
          }
        },
      })
    },

    // 预览图片
    previewImg(imgs) {
      uni.previewImage({
        urls: imgs,
        current: 0,
      })
    },

    // 保存
    async save() {
      uni.showLoading({
        title: '保存中',
      })

      if (this.productList.length === 0) {
        uni.showToast({
          title: '请添加至少一个商品',
          icon: 'none',
        })
        return false
      }
      console.log(this.serveList)
      let data = {
        arriveId: this.$store.state.afterSales.arrvialId,
        products: this.productList.map((item) => ({
          productId: item.id,
          productName: item.goods_Name,
          costPrice: item.isVisualGoods ? 0 : item.in_Price,
          rateIncrease: item.added_Rate,
          count: item.amount,
        })),
        services: this.serveList.map((item) => ({
          serviceTypeId: item.serviceId,
          // service_Calculate_Rule_id: item.maintenance_Type_Id,
          service_Calculate_Rule_id: item.service_Calculate_Rule_id,
          serviceName: item.service_Name,
          servicePrice: Number(item.service_Price),
          serviceCount: item.serviceNum,
          couponId: null,
          couponMoney: 0,
        })),
        exceptionIds:
          this.errList.length !== 0
            ? this.errList.map((item) => item.exceptionId)
            : [],
        // "cuopons": [],
        method: this.installMode.id,
        reason: this.remark,
        freight: this.freightVal ? parseFloat(this.freightVal) : 0,
      }
      try {
        const res = await this.$api.afterSales.AddNewOrder(data)
        uni.hideLoading()
        uni.redirectTo({
          url:
            '/pages_afterSales/submitOrderDetail/submitOrderDetail?id=' +
            res.data,
        })
      } catch (err) {
        console.log(err)
      }
    },

    // 跳转到关联检测异常列表页面
    goErrorPage() {
      uni.navigateTo({
        url: '/pages_afterSales/relatError/relatError',
      })
    },
  },
}
